package org.apache.jmeter.protocol.http.sampler;

import org.apache.commons.lang3.StringUtils;
import org.apache.jmeter.engine.event.LoopIterationEvent;
import org.apache.jmeter.protocol.http.control.HeaderManager;
import org.apache.jmeter.samplers.Interruptible;
import org.apache.jmeter.testelement.property.CollectionProperty;
import org.apache.jmeter.testelement.property.JMeterProperty;
import org.apache.jmeter.threads.JMeterVariables;

/**
 * @author guobingbing
 * @version 1.0
 * @wechat t_gbinb
 * @create 2021/8/11 11:08
 */
public class HttpRequestSampler extends HTTPSamplerBase implements Interruptible {

	private static final long serialVersionUID = 1L;

	private transient HTTPAbstractImpl impl;

	public HttpRequestSampler(){
		super();
	}

	/**
	 * Convenience method used to initialise the implementation.
	 *
	 * @param impl the implementation to use.
	 */
	public HttpRequestSampler(String impl){
		super();
		setImplementation(impl);
	}

	/** {@inheritDoc} */
	@Override
	protected HTTPSampleResult sample(java.net.URL u, String method, boolean areFollowingRedirect, int depth) {
		if (impl == null) {
			try {
				impl = HTTPSamplerFactory.getImplementation(getImplementation(), this);
			} catch (Exception ex) {
				return errorResult(ex, new HTTPSampleResult());
			}
		}
		HTTPSampleResult result = impl.sample(u, method, areFollowingRedirect, depth);
		//result.setDataType("json");
		return result;
	}

	@Override
	public void threadFinished(){
		if (impl != null){
			impl.threadFinished();
		}
	}

	@Override
	public boolean interrupt() {
		if (impl != null) {
			return impl.interrupt();
		}
		return false;
	}

	/**
	 *
	 */
	@Override
	public void testIterationStart(LoopIterationEvent event) {
		if (impl != null) {
			impl.notifyFirstSampleAfterLoopRestart();
		}
	}

	/**
	 * {@inheritDoc}
	 */
	@Override
	public void testStarted() {
		JMeterVariables vars = this.getThreadContext().getVariables();
		Object defaultConf = vars.getObject(HTTPSamplerBase.DEFAULT_CONFIG);
		if(defaultConf!=null){
			CollectionProperty properties = (CollectionProperty)defaultConf;
			for (JMeterProperty prop : properties) {
				if (StringUtils.isBlank(getPropertyAsString(prop.getName()))) {
					setProperty(prop.getName(), prop.getStringValue());
				}
			}
		}
		HeaderManager headerManager = (HeaderManager) vars.getObject(HEADER_MANAGER);
		if(headerManager!=null){
			this.setHeaderManager(headerManager);
		}
	}
}
